<template>
    <div ref="googleAdStyle">
        <ins
            class="adsbygoogle"
            :style="`display:block;width:100%;height:${height}`"
            :data-ad-channel="channel"
            data-ad-client="ca-pub-6468790746781495"
            :data-ad-slot="id"
            :data-anchor-ad="anchorAd"
            data-full-width-responsive="true"
        ></ins>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const props = defineProps({
    id: {
        type: String,
        required: true
    },
    height: {
        type: String,
        default: '100%'
    },
    anchorAd: {
        type: Boolean,
        default: false
    },
    parentPage: {
        type: String,
        default: ''
    },
    channel: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['adSuccess', 'adError'])
const googleAdStyle = ref(null)
let observer = null
let hasReported = false  // 添加标记防止重复上报

const handleIntersection = (entries) => {
    if (entries[0].isIntersecting) {
        const adContainer = googleAdStyle.value
        const adElement = adContainer.querySelector('.adsbygoogle')

        // Create MutationObserver to monitor ad status
        const adObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.attributeName === 'data-ad-status' && !hasReported) {
                    const status = adElement.getAttribute('data-ad-status')
                    if (status === 'filled') {
                        hasReported = true
                        emit('adSuccess')
                        logEvent('AD_Show', {
                            Page: props.parentPage
                        });
                    } else if (status === 'unfilled') {
                        hasReported = true
                        emit('adError')
                        logEvent('AD_Show_Fail', {
                            Page: props.parentPage
                        });
                        // Remove unfilled ad container
                        adElement.remove()
                    }
                    adObserver.disconnect()
                }
            })
        })

        // Start observing ad element
        adObserver.observe(adElement, {
            attributes: true,
            attributeFilter: ['data-ad-status']
        })

        // Push ad for display
        try {
            (window.adsbygoogle = window.adsbygoogle || []).push({})
        } catch (error) {
            console.error('AdSense push error:', error)
            emit('adError')
            logEvent('AFC_AD_Error', {
                AdSlot: props.id,
                Page: props.parentPage,
                Error: error.message
            })
        }

        // Stop intersection observing
        observer.unobserve(adContainer)
    }
}

onMounted(() => {
    observer = new IntersectionObserver(handleIntersection)
    observer.observe(googleAdStyle.value)
})

onUnmounted(() => {
    if (observer) {
        observer.disconnect()
        observer = null
    }
})
</script>

<style scoped>
/* Add any custom styles here */
</style> 